package com.itrip.listener;

import com.itrip.service.OrderService;
import com.itrip.service.TempleStoreService;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Resource
    private OrderService orderService;

    @Resource
    private TempleStoreService templeStoreService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取失效的key
        String expiredKey = message.toString();
        //获取订单号
        String orderStr=expiredKey.substring(expiredKey.indexOf(":")+1,expiredKey.indexOf(","));
        Long orderNo=Long.parseLong(orderStr);
        System.out.println(orderNo);

        //获取库存减少量
        String reductionStr=expiredKey.substring(expiredKey.indexOf(",")+1,expiredKey.lastIndexOf(","));
        Integer reduction=Integer.parseInt(reductionStr);
        System.out.println(reduction);

        //获取房间id
        String roomStr=expiredKey.substring(expiredKey.lastIndexOf(",")+1);
        Long roomId = Long.parseLong(roomStr);
        System.out.println(roomId);

        /*判断订单状态*/
        //获取订单状态
        int status = orderService.selectOrderStatus(roomId);
        if(status==1){
            //库存room房间数增加删改的那些,hotelId和roomId
               //获取hotelId
            Integer hotelId = orderService.getHotelId(orderNo);
            System.out.println(hotelId);
              //修改store中的数量
                templeStoreService.modifyStore(hotelId,roomId);
            //插入订单记录,修改订单状态为5,已失效
            orderService.setOrderInvalidate(orderNo.toString());
        }
        System.out.println("失效key："+expiredKey);
    }
}